// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database()
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const {
            type,
            userId,
            status,
            pageNum,
            pageSize
        } = event

        // 验证参数
        if (!type || !userId || status === undefined || pageNum === undefined || pageSize === undefined) {
            return {
                success: false,
                message: '参数缺失'
            }
        }

        // 构建查询条件
        let queryCondition = {
            status: status,
            isDeleted: false
        }

        // 根据类型设置不同的查询条件
        if (type === 'sell') {
            queryCondition.sellerId = userId
        } else if (type === 'buy') {
            queryCondition.buyerId = userId
        } else {
            return {
                success: false,
                message: '查询类型错误'
            }
        }

        // 执行查询
        const orders = await db.collection('orders')
            .where(queryCondition)
            .orderBy('createTime', 'desc')
            .skip((pageNum - 1) * pageSize)
            .limit(pageSize)
            .get()

        // 如果没有订单，直接返回
        if (!orders.data || orders.data.length === 0) {
            return {
                success: true,
                orders: []
            }
        }

        // 提取所有订单中的goodsId
        const goodsIds = orders.data.map(order => order.goodsId)

        // 批量查询商品详情
        const goodsMap = {}
        if (goodsIds.length > 0) {
            const goodsResult = await db.collection('blindbox_goods')
                .where({
                    _id: _.in(goodsIds)
                })
                .get()

            // 构建商品ID到商品详情的映射
            goodsResult.data.forEach(goods => {
                goodsMap[goods._id] = goods
            })
        }

        // 将商品详情合并到订单数据中
        const ordersWithGoods = orders.data.map(order => {
            const goodsInfo = goodsMap[order.goodsId] || {}
            return {
                ...order,
                goodsInfo: {
                    goodsName: goodsInfo.goodsName || '商品已删除',
                    goodsImage: goodsInfo.goodsImage || '',
                    goodsPrice: goodsInfo.goodsPrice || 0,
                    shippingFee: goodsInfo.shippingFee || 0,
                    ipId:goodsInfo.ipId,
                    ipName:goodsInfo.ipName,
                    seriesId:goodsInfo.seriesId,
                    seriesName:goodsInfo.seriesName,
                    productId:goodsInfo.productId,
                    productName:goodsInfo.productName,
                }
            }
        })

        return {
            success: true,
            orders: ordersWithGoods
        }

    } catch (error) {
        console.error('查询订单失败:', error)
        return {
            success: false,
            message: error.message || '查询订单失败'
        }
    }
}